package com.zgm.utils.ui;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.EditText;

/**
 * Created by 张公铭 on 2017/6/29 0029.
 * 右侧图标功能的文本框
 */

public class MyEditText extends EditText
{
    private onDrawableRightListener mRightListener;
    final int DRAWABLE_RIGHT = 2;

    public MyEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    /**
     * 绑定监听事件
     *
     * @param listener onDrawableRightListener
     */
    public void setDrawableRightListener(onDrawableRightListener listener)
    {
        this.mRightListener = listener;
    }

    /**
     * 监听回调接口
     */
    public interface onDrawableRightListener
    {
        public void onDrawableRightClick(EditText view);
    }

    //判断点击位置是否是右侧图标，如果是执行相应的回调函数。
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_UP:
                if (mRightListener != null)
                {
                    Drawable drawableRight = getCompoundDrawables()[DRAWABLE_RIGHT];
                    if (drawableRight != null && event.getRawX() >= (getRight() - drawableRight.getBounds().width()))
                    {
                        mRightListener.onDrawableRightClick(this);
                    }
                }
                break;
        }
        return super.onTouchEvent(event);
    }
}
